package com.rub.android.utils.parser

import android.content.Context
import androidx.annotation.NonNull
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.StringBuilder


object FileReader {

    fun readFileFromAsset(@NonNull context: Context, @NonNull fileName: String?): String? {
        try {
            val inputStream = context.assets.open(fileName!!)
            val result = readFileFromInputStream(inputStream)
            inputStream.close()
            return result
        } catch (e: IOException) {
            e.printStackTrace() // TODO
        }
        return null
    }

    fun readFileFromInputStream(@NonNull inputStream: InputStream?): String? {
        val inputStreamReader = InputStreamReader(inputStream)
        val bufferedReader = BufferedReader(inputStreamReader)
        val result = StringBuilder()
        var line: String?
        try {
            while (bufferedReader.readLine().also { line = it } != null) {
                result.append(line)
            }
            return result.toString()
        } catch (exception: IOException) {
        } finally {
            try {
                bufferedReader.close()
            } catch (e2: IOException) {
            }
            try {
                inputStreamReader.close()
            } catch (e2: IOException) {
            }
        }
        return null
    }
}